<?php

namespace Home\Controller;

use Think\Controller;
use Common\Controller\WapController;

class IndexController extends WapController
{

    public function index()
    {

        $category = M("reziti_category")->order("seq asc")->select();
        $url = $_SERVER["QUERY_STRING"];
        $this->assign("url", $url);
        $this->assign("category", $category);
        $this->display();
    }

    public function fn_GetSiteType($refer)
    {
        $type = null;
        $site = M("site")->where(array("name" => $refer))->find();
        if ($site) {
            $type = $site['type'];
        }
        return $type;
    }

    public function apply_pay()
    {

        $order = M("order")->where(array("id" => I("get.uuid")))->find();
        $this->assign("apply_info", $order);

        $type = $this->fn_GetSiteType($_SERVER['SERVER_NAME']);
        $service = M("service")->where(array("type" => $type))->order("seq asc")->select();
        $this->assign("service", $service);

        //第二项为默认选择项
        $default = $service[1];
        $this->assign("default", $service[1]);

        $this->display();
    }

    private function fn_GetWeekOfToday()
    {
        $weekarray = array("天", "一", "二", "三", "四", "五", "六");
        return "星期" . $weekarray[date("w")];
    }

    private function fn_GetQqOfToday()
    {
        $week = $this->fn_GetWeekOfToday();
        $kefu = M("kefu")->where(array("week" => $week))->find();
        return $kefu['qq'];
    }

    public function apply_submit()
    {
        $type = $this->fn_GetSiteType($_SERVER['SERVER_NAME']);
        if ($type <= 0) {
            $this->error("下单失败，请联系管理员");
        }
        $data = array(
            "no" => $this->fn_GenerateOrderNo(),
            "nickname" => I("post.wx_name"),
            "name" => I("post.user_name"),
            "phone" => I("post.user_tel"),
            "purpose" => I("post.purpose"),
            "qq" => I("post.qq"),
            "wxgzh" => I("post.mp_name"),
            "service_type" => $type,
            "province" => I("post.province"),
            "city" => I("post.city"),
            "area" => I("post.area"),
            "refer" => I("post.user_refer"),
            "client" => I("post.user_client"),
            "address" => I("post.province") . I("post.city") . I("post.area"),
            "money" => 0.00,
            "cuser" => "customer",
            "ctime" => date("Y/m/d H:i:s"),
            "state" => "未支付",
            "url" => I("post.url"),
        );
        $uuid = M("order")->add($data);
        if ($uuid) {
            $this->success($uuid);
        }
        $this->error("提交失败");
    }

    /* 微信H5支付回调方法 */
    public function wechat_h5_finish()
    {
        /**
         * {"appid":"wx373c3b608fe3e39e","attach":"sdsdafsadf",
         * "bank_type":"CFT","cash_fee":"1","fee_type":"CNY",
         * "is_subscribe":"N","mch_id":"1500774721",
         * "nonce_str":"husfie60utgs2qthhjpf25pkba1m05ie",
         * "openid":"oZVPgjkTT9UdsaixyEL9HwblNlcg",
         * "out_trade_no":"1500774721201803281142370000",
         * "result_code":"SUCCESS","return_code":"SUCCESS",
         * "sign":"7E4689F03F0E832E25099BED9F0F9B30","time_end":"20180328114256",
         * "total_fee":"1","trade_type":"NATIVE",
         * "transaction_id":"4200000092201803287063058016"}
         *  [2018-03-28 11:42:56][debug] query:{"appid":"wx373c3b608fe3e39e",
         * "attach":"sdsdafsadf","bank_type":"CFT","cash_fee":"1",
         * "fee_type":"CNY","is_subscribe":"N","mch_id":"1500774721",
         * "nonce_str":"IcduhUfbVgp70XN8","openid":"oZVPgjkTT9UdsaixyEL9HwblNlcg",
         * "out_trade_no":"1500774721201803281142370000","result_code":"SUCCESS",
         * "return_code":"SUCCESS","return_msg":"OK","sign":"1AF6D37649D661E5376D2F2ABDCE9D45",
         * "time_end":"20180328114256","total_fee":"1","trade_state":"SUCCESS","trade_state_desc":"\u652f\u4ed8\u6210\u529f",
         * "trade_type":"NATIVE","transaction_id":"4200000092201803287063058016"}
         */
        require_once $_SERVER['DOCUMENT_ROOT'] . "/api/WechatPay/example/notify.php";
        $result = $notify->result;
        $uuid = I("get.uuid");
        if ($result) {
            if ($result['result_code'] == 'SUCCESS') {
                $data = array(
                    "payid" => $result['transaction_id'],
                    "ptime" => date("Y-m-d H:i:s"),
                    "state" => "已支付",
                );
                $where = array("no" => $result['out_trade_no'], "sendsms" => "0");
                $order = M("order")->where($where)->find();
                if ($order) {
                    sendSMS($order['phone'], $order['no']);
                    $data['sendsms'] = "1";
                }

                $res = M("order")->where($where)->save($data);
                if (!$res) {
                    $str = "微信H5支付-订单：" . $result['out_trade_no'] . "支付成功。
                后台数据更新失败,支付时间：" . $data['ptime'] .
                        "支付单号：" . $result['transaction_id'];
                    file_put_contents("log.txt", $str . "\r\n", FILE_APPEND);
                }
            } else {
                $this->assign("state", "error");
            }
        }
        /*else{
            $this->assign("state", "error");
        }*/
        $this->assign("qq", $this->fn_GetQqOfToday());
        $order = M("order")->where(array("id" => $uuid))->find();
        $this->assign("apply_info", $order);
        $this->display();
    }

    // 生成订单号
    private function fn_GenerateOrderNo()
    {
        return date('YmdHis') . rand(100, 999);
    }

    public function apply_topay()
    {

        $this->display();
    }

    /* 微信h5支付 */
    public function wechat_h5()
    {
        /**
         * array(10) {
         *      ["return_code"]=> string(7) "SUCCESS"
         *      ["return_msg"]=> string(2) "OK"
         *      ["appid"]=> string(18) "wx373c3b608fe3e39e"
         *      ["mch_id"]=> string(10) "1500774721"
         *      ["nonce_str"]=> string(16) "w0t9fL8lPN5vXLWr"
         *      ["sign"]=> string(32) "3E9767D72D6530175543AF736470380D"
         *      ["result_code"]=> string(7) "SUCCESS"
         *      ["prepay_id"]=> string(36) "wx201803290057099eef89053d0185200279"
         *      ["trade_type"]=> string(4) "MWEB"
         *      ["mweb_url"]=> string(118) "https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx201803290057099eef89053d0185200279&package=3153254182"
         * }
         */
        require_once $_SERVER['DOCUMENT_ROOT'] . "/api/WechatPay/lib/WxPay.Config.php";

        $appid = \WxPayConfig::APPID;//微信给的
        $mch_id = \WxPayConfig::MCHID;//微信官方的x
        $key = \WxPayConfig::KEY;//自己设置的微信商家key
        $userip = get_client_ip(); //获得用户设备IP 自己网上百度去
        $spbill_create_ip = $userip; //IP

        $uuid = I("post.uuid");
        $order = M("order")->where(array("id" => $uuid))->find();
        if (!$order) {
            $this->error("参数传递错误");
        }
        if ($order['state'] == '已支付') {
            $this->error("该订单已经完成支付，请不要重复操作");
        }

        $rand = rand(00000, 99999);
        $out_trade_no = $order['no'];//平台内部订单号
        $nonce_str = MD5($out_trade_no);//随机字符串
        $body = $order['service'];//内容
        $total_fee = floatval($order['money']) * 100; //金额
        if (C("PAY_DEBUG")) {
            $total_fee = 1;
        }
        $notify_url = C("SITE_URL") . "/home/index/wechat_h5_finish/uuid/" . $uuid; //回调地址
        $trade_type = 'MWEB';//交易类型 具体看API 里面有详细介绍
        $scene_info = '{"h5_info":{"type":"Wap","wap_url":"' . C("SITE_URL") . '","wap_name":"微信H5支付"}}';//场景信息 必要参数

        $signA = "appid=$appid&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";

        $strSignTmp = $signA . "&key=$key"; //拼接字符串  注意顺序微信有个测试网址 顺序按照他的来 直接点下面的校正测试 包括下面XML  是否正确
        $sign = strtoupper(MD5($strSignTmp)); // MD5 后转换成大写
        $post_data = "<xml>
                        <appid>$appid</appid>
                        <body>$body</body>
                        <mch_id>$mch_id</mch_id>
                        <nonce_str>$nonce_str</nonce_str>
                        <notify_url>$notify_url</notify_url>
                        <out_trade_no>$out_trade_no</out_trade_no>
                        <scene_info>$scene_info</scene_info>
                        <spbill_create_ip>$spbill_create_ip</spbill_create_ip>
                        <total_fee>$total_fee</total_fee>
                        <trade_type>$trade_type</trade_type>
                        <sign>$sign</sign>
                    </xml>";//拼接成XML 格式
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信传参地址
        $dataxml = http_post($url, $post_data); //后台POST微信传参地址  同时取得微信返回的参数    POST 方法我写下面了
        $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); //将微信返回的XML 转换成数组
        if ($objectxml['return_code'] != "SUCCESS") {
            $this->error($objectxml["return_msg"]);
        }
        $this->success($objectxml["mweb_url"] . '&redirect_url=' . $notify_url);
        //header("Location: ".$objectxml["mweb_url"]);
        /*echo "<pre>";
        var_dump($objectxml);
        echo '<hr>';*/
    }

    /* 微信扫码支付 */
    public function wechat_saoma()
    {
        ini_set('date.timezone', 'Asia/Shanghai');
        require_once $_SERVER['DOCUMENT_ROOT'] . "/api/WechatPay/lib/WxPay.Api.php";
        require_once $_SERVER['DOCUMENT_ROOT'] . "/api/WechatPay/example/WxPay.NativePay.php";
        //require_once $_SERVER['DOCUMENT_ROOT'].'/api/WechatPay/example/log.php';

        $uuid = I("get.uuid");
        $order = M("order")->where(array("id" => $uuid))->find();
        if (!$order) {
            $this->error("参数传递错误");
        }
        if ($order['state'] == '已支付') {
            $this->error("该订单已经完成支付，请不要重复操作");
        }
        //如果该订单已经设置了qrcode，则需要重新创建订单
        if ($order['qrcode']) {
            $data = array(
                "no" => $this->fn_GenerateOrderNo(),
                "nickname" => $order['nickname'],
                "name" => $order['name'],
                "phone" => $order['phone'],
                "purpose" => $order['purpose'],
                "qq" => $order['qq'],
                "wxgzh" => $order['wxgzh'],
                "province" => $order['province'],
                "city" => $order['city'],
                "area" => $order['area'],
                "type" => $order['type'],
                "client" => $order['client'],
                "refer" => $order['refer'],
                "service" => $order['service'],
                "money" => $order['money'],
                "address" => $order['address'],
                "cuser" => "customer",
                "ctime" => date("Y/m/d H:i:s"),
                "state" => "未支付",
            );
            $uuid = M("order")->add($data);
            if ($uuid) {
                $order = M("order")->where(array("id" => $uuid))->find();
            } else {
                echo '订单创建失败，请刷新页面重试一次';
                exit;
            }
        }
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($order['service']);
        $input->SetAttach($order['service']);
        $input->SetOut_trade_no($order['no']);
        $input->SetTotal_fee(floatval($order['money']) * 100);
        if (C("PAY_DEBUG")) {
            $input->SetTotal_fee("1");
        }
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($order['service']);
        $input->SetNotify_url(C("SITE_URL") . "/home/index/pay_finish2");
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($order['id'] . "-100000");
        $notify = new \NativePay();
        $result = $notify->GetPayUrl($input);
        $url2 = $result["code_url"];

        $data = array("qrcode" => $url2, "utime" => time());
        $res = M("order")->where(array("id" => $uuid))->save($data);
        if (!$res) {
            $this->error(M("order")->getLastSql());
            $this->error("二维码更新错误");
        }
        $this->assign("qq", $this->fn_GetQqOfToday());
        $this->assign("price", $order['money']);
        $this->assign("uuid", $order['id']);
        $this->assign("qrcode", $url2);
        $this->display();
    }

    /* todo 微信公众号支付 */
    public function wechat_jsapi()
    {
        ini_set('date.timezone', 'Asia/Shanghai');
        require_once $_SERVER['DOCUMENT_ROOT'] . "/api/WechatPay/lib/WxPay.Api.php";
        require_once $_SERVER['DOCUMENT_ROOT'] . "/api/WechatPay/example/WxPay.JsApiPay.php";

        $uuid = I("get.uuid");

        //①、获取用户openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();

        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("test");
        $input->SetAttach("test");
        $input->SetOut_trade_no(\WxPayConfig::MCHID . date("YmdHis"));
        if (C("PAY_DEBUG")) {
            $input->SetTotal_fee("1");
        }
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url(C("SITE_URL") . "/home/index/pay_finish2");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->assign($jsApiParameters);
        $this->display();

        //③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
        /**
         * 注意：
         * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
         * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
         * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
         */
    }

    /* 支付宝手机网站支付 */
    public function alipay_wap()
    {
        require_once $_SERVER['DOCUMENT_ROOT'] . '/api/AliWapPay/wappay/service/AlipayTradeService.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/api/AliWapPay/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php';
        require $_SERVER['DOCUMENT_ROOT'] . '/api/AliWapPay/config.php';

        $uuid = I("get.uuid");
        $order = M("order")->where(array("id" => $uuid))->find();
        if (!$order) {
            $this->error("参数传递错误");
        }
        if ($order['state'] == '已支付') {
            $this->error("该订单已经完成支付，请不要重复操作");
        }

        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $order['no'];
        //订单名称，必填
        $subject = $order['service'];
        //付款金额，必填
        $total_amount = $order['money'];
        if (C("PAY_DEBUG")) {
            $total_amount = 0.01;
        }
        //商品描述，可空
        $body = $order['service'];
        //超时时间
        $timeout_express = "1m";

        $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setTimeExpress($timeout_express);
        $config['notify_url'] = C("SITE_URL") . "/home/index/pay_finish";
        $config['return_url'] = C("SITE_URL") . "/home/index/alipay_wap_finish";
        $payResponse = new \AlipayTradeService($config);
        $result = $payResponse->wapPay($payRequestBuilder, $config['return_url'], $config['notify_url']);

        return;
    }

    /* 支付宝手机网站支付成功，同步跳转页面 */
    public function alipay_wap_finish()
    {
        /**
         * Array ( [total_amount] => 0.01 [timestamp] => 2018-03-28 00:18:31
         * [sign] => dvJ9e+WuHGh37AHffaj9Gb+5SxX6u0H7i1qrYPXz4hLS+vken386bSvtNFiX/Bil8fB6fB7ULuR5pe9I3EcT1fNFNSZtyiFt6aAlmEVUYbzx56HJZNhcSfjptbMy6EkGI1xrllbidHGDdbu6xepHqgQpUCRh2tYnTf8/tJVYSaCSXotlasSN7xwk9SdWl3YwQXhi7mPhXQ6+QOBhZgwe0neJjFgkomYktV8CxjGeRr7k3iXqfoH/aKwZvDEvJSvAEFUoeBLtbQLBD+WG36tmYe466Rv2Bk4WkCK2MD8wooYy1VyJ7R4T8MwD7gGGz1j/2RTfCh9C6opsVclG5XVGpg==
         * [trade_no] => 2018032821001004650586768845
         * [sign_type] => RSA2 [auth_app_id] => 2018032702453539 [charset] => UTF-8
         * [seller_id] => 2088031632394513 [method] => alipay.trade.wap.pay.return
         * [app_id] => 2018032702453539 [out_trade_no] => 213213213123 [version] => 1.0 )
         */
        $this->assign("price", $_REQUEST['total_amount']);
        $this->assign("order_no", $_REQUEST['out_trade_no']);
        $this->assign("qq", $this->fn_GetQqOfToday());
        if ($_REQUEST['trade_status'] == 'TRADE_SUCCESS' || $_REQUEST['trade_no']) {
            $data = array(
                "payid" => $_REQUEST['trade_no'],
                "ptime" => $_REQUEST['gmt_payment'],
                "state" => "已支付",
            );
            $where = array("no" => $_REQUEST['out_trade_no'], "sendsms" => "0");
            $order = M("order")->where($where)->find();
            if ($order) {
                sendSMS($order['phone'], $order['no']);
                $data['sendsms'] = "1";
            }

            $res = M("order")->where($where)->save($data);
            if (!$res) {
                $str = "支付宝-订单：" . $_REQUEST['out_trade_no'] . "支付成功。
                后台数据更新失败,支付时间：" . $_REQUEST['gmt_payment'] .
                    "支付单号：" . $_REQUEST['trade_no'];
                file_put_contents("log.txt", $str . "\r\n", FILE_APPEND);
            }
        } else {
            $this->assign("state", "error");
        }
        $this->display();
    }

    /* 支付宝面对面支付 */
    public function alipay_f2f()
    {
        require_once $_SERVER['DOCUMENT_ROOT'] . '/api/AliF2fPay/f2fpay/model/builder/AlipayTradePrecreateContentBuilder.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/api/AliF2fPay/f2fpay/service/AlipayTradeService.php';

        $uuid = I("get.uuid");
        $order = M("order")->where(array("id" => $uuid))->find();
        if (!$order) {
            $this->error("参数传递错误");
        }
        if ($order['state'] == '已支付') {
            $this->error("该订单已经完成支付，请不要重复操作");
        }
        //如果该订单已经设置了qrcode，则需要重新创建订单
        if ($order['qrcode']) {
            $data = array(
                "no" => $this->fn_GenerateOrderNo(),
                "nickname" => $order['nickname'],
                "name" => $order['name'],
                "phone" => $order['phone'],
                "purpose" => $order['purpose'],
                "qq" => $order['qq'],
                "wxgzh" => $order['wxgzh'],
                "province" => $order['province'],
                "city" => $order['city'],
                "area" => $order['area'],
                "type" => $order['type'],
                "client" => $order['client'],
                "refer" => $order['refer'],
                "service" => $order['service'],
                "money" => $order['money'],
                "address" => $order['address'],
                "cuser" => "customer",
                "ctime" => date("Y/m/d H:i:s"),
                "state" => "未支付",
            );
            $uuid = M("order")->add($data);
            if ($uuid) {
                $order = M("order")->where(array("id" => $uuid))->find();
            } else {
                echo '订单创建失败，请刷新页面重试一次';
                exit;
            }
        }
        ////////////////////////////   支付发起   //////////////////////
        // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
        // 需保证商户系统端不能重复，建议通过数据库sequence生成，
        //$outTradeNo = "qrpay".date('Ymdhis').mt_rand(100,1000);
        $outTradeNo = $order['no'];

        // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
        $subject = $order['service'];

        // (必填) 订单总金额，单位为元，不能超过1亿元
        // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
        $totalAmount = floatval($order['money']);
        if (C("PAY_DEBUG")) {
            $totalAmount = 0.01;
        }

        // (不推荐使用) 订单可打折金额，可以配合商家平台配置折扣活动，如果订单部分商品参与打折，可以将部分商品总价填写至此字段，默认全部商品可打折
        // 如果该值未传入,但传入了【订单总金额】,【不可打折金额】 则该值默认为【订单总金额】- 【不可打折金额】
        //String discountableAmount = "1.00"; //

        // (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
        // 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
        //$undiscountableAmount = "0.01";

        // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
        // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
        //$sellerId = "";

        // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
        $body = $order['service'] . "服务费:" . $order['price'];

        //商户操作员编号，添加此参数可以为商户操作员做销售统计
        //$operatorId = "test_operator_id";

        // (可选) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
        //$storeId = "test_store_id";

        // 支付宝的店铺编号
        //$alipayStoreId= "test_alipay_store_id";

        // 业务扩展参数，目前可添加由支付宝分配的系统商编号(通过setSysServiceProviderId方法)，系统商开发使用,详情请咨询支付宝技术支持
        $providerId = ""; //系统商pid,作为系统商返佣数据提取的依据
        $extendParams = new \ExtendParams();
        $extendParams->setSysServiceProviderId($providerId);
        $extendParamsArr = $extendParams->getExtendParams();

        // 支付超时，线下扫码交易定义为5分钟
        $timeExpress = "5m";

        // 商品明细列表，需填写购买商品详细信息，
        $goodsDetailList = array();

        // 创建一个商品信息，参数含义分别为商品id（使用国标）、名称、单价（单位为分）、数量，如果需要添加商品类别，详见GoodsDetail
        $goods1 = new \GoodsDetail();
        $goods1->setGoodsId($order['id'] . "-100000");
        $goods1->setGoodsName($order['service']);
        $goods1->setPrice($order['price']);
        $goods1->setQuantity(1);
        //得到商品1明细数组
        $goods1Arr = $goods1->getGoodsDetail();
        $goodsDetailList = array($goods1Arr);

        //第三方应用授权令牌,商户授权系统商开发模式下使用
        $appAuthToken = "";//根据真实值填写

        // 创建请求builder，设置请求参数
        $qrPayRequestBuilder = new \AlipayTradePrecreateContentBuilder();
        $qrPayRequestBuilder->setOutTradeNo($outTradeNo);
        $qrPayRequestBuilder->setTotalAmount($totalAmount);
        $qrPayRequestBuilder->setTimeExpress($timeExpress);
        $qrPayRequestBuilder->setSubject($subject);
        $qrPayRequestBuilder->setBody($body);
        //$qrPayRequestBuilder->setUndiscountableAmount($undiscountableAmount);
        $qrPayRequestBuilder->setExtendParams($extendParamsArr);
        $qrPayRequestBuilder->setGoodsDetailList($goodsDetailList);
        //$qrPayRequestBuilder->setStoreId($storeId);
        //$qrPayRequestBuilder->setOperatorId($operatorId);
        //$qrPayRequestBuilder->setAlipayStoreId($alipayStoreId);
        $qrPayRequestBuilder->setAppAuthToken($appAuthToken);

        // 调用qrPay方法获取当面付应答
        $config['notify_url'] = C("SITE_URL") . "/home/index/pay_finish";
        $config['return_url'] = C("SITE_URL") . "/home/index/alipay_wap_finish";
        $qrPay = new \AlipayTradeService($config);
        $qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);

        //	根据状态值进行业务处理
        switch ($qrPayResult->getTradeStatus()) {
            case "SUCCESS":
                //echo "支付宝创建订单二维码成功:"."<br>---------------------------------------<br>";
                $response = $qrPayResult->getResponse();
                $qrcode = $response->qr_code;
                $data = array("qrcode" => $qrcode, "utime" => time());
                $res = M("order")->where(array("id" => $uuid))->save($data);
                if (!$res) {
                    $this->error("二维码更新错误");
                }
                $this->assign("qrcode", $qrcode);
                /*$qrcode += "?uuid=1";
                $qrcode = urlencode($qrcode);*/
                //echo "<img src='http://pan.baidu.com/share/qrcode?w=200&h=200&url=".$qrcode."' />";
                //$qrcode = $qrPay->create_erweima($response->qr_code);
                //echo $qrcode;
                //print_r($response);

                break;
            case "FAILED":
                echo "支付宝创建订单二维码失败!!!" . "<br>--------------------------<br>";
                if (!empty($qrPayResult->getResponse())) {
                    print_r($qrPayResult->getResponse());
                }
                break;
            case "UNKNOWN":
                echo "系统异常，状态未知!!!" . "<br>--------------------------<br>";
                if (!empty($qrPayResult->getResponse())) {
                    print_r($qrPayResult->getResponse());
                }
                break;
            default:
                echo "不支持的返回状态，创建订单二维码返回异常!!!";
                break;
        }
        $this->assign("qq", $this->fn_GetQqOfToday());
        $this->assign("uuid", $uuid);
        $this->assign("price", $order['money']);
        $this->display();
    }

    /* 支付宝网站支付 */
    public function alipay_web()
    {

        require_once $_SERVER['DOCUMENT_ROOT'] . '/api/AliWeb/config.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/api/AliWeb/AopSdk.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/api/AliWeb/pagepay/service/AlipayTradeService.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/api/AliWeb/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';

        $uuid = I("request.uuid");
        $order = M("order")->where(array("id" => $uuid))->find();
        if (!$order) {
            $this->error("参数传递错误");
        }
        if ($order['state'] == '已支付') {
            $this->error("该订单已经完成支付，请不要重复操作");
        }

        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = trim($order['no']);
        //订单名称，必填
        $subject = trim($order['service']);
        //付款金额，必填
        $total_amount = floatval($order['money']);
        if (C("PAY_DEBUG")) {
            $total_amount = 0.01;
        }

        //商品描述，可空
        $body = $order['service'] . "服务费:" . $order['price'];

        //构造参数
        $payRequestBuilder = new \AlipayTradePagePayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setOutTradeNo($out_trade_no);

        // 调用qrPay方法获取当面付应答
        $config['notify_url'] = C("SITE_URL") . "/home/index/pay_finish";
        $config['return_url'] = C("SITE_URL") . "/home/index/alipay_wap_finish";
        $aop = new \AlipayTradeService($config);

        /**
         * pagePay 电脑网站支付请求
         * @param $builder 业务参数，使用buildmodel中的对象生成。
         * @param $return_url 同步跳转地址，公网可以访问
         * @param $notify_url 异步通知地址，公网可以访问
         * @return $response 支付宝返回的信息
         */
        $response = $aop->pagePay($payRequestBuilder, $config['return_url'], $config['notify_url']);

        //输出表单
        var_dump($response);
        exit;
        //http://wxgzh.vshoutao.com/home/index/alipay_wap_finish?
        //total_amount=0.01&
        //timestamp=2018-04-15+21%3A57%3A35&sign=Fbq11oTUae%2BtbyZS1hSpF7jaKulTgodKQO7ouXBuMibSt9VB2AdXos2AELjODOw1gZTNtkhrlEn1ZYGUZM2R0qaIzueeCx%2BPkVzFdXPokbXHitAaKy48f7YPpiJ3I0nGOm03ik%2FDgygyiLhxa0YC%2Fu1QwPti7yTBjPbbn4epISZYBL6D50B8T8gWbS3oMNID%2FD7ak0pGqux5h7QxQPHaMsbgN3znoP52l%2BOSDkQOD6slxs8CVLZ1FkAx148wHilHugw0gqZQxxW6N51SPEiQiU0WLN8i8XMhedc4CJOQid2Ploam%2Fz%2FhJtJ%2B40EgrEsNnCD7j3wpm1GKLfs4hpte%2FA%3D%3D
        //&trade_no=2018041521001004650274427893
        //&sign_type=RSA2
        //&auth_app_id=2018032702453539&charset=UTF-8
        //&seller_id=2088031632394513
        //&method=alipay.trade.page.pay.return&
        //app_id=2018032702453539&out_trade_no=20180415204934669&version=1.0
    }

    /* 支付宝面对面支付回调方法, f2f,wap回调结果的格式是一样的 */
    public function pay_finish()
    {
        /** wap
         * Array ( [gmt_create] => 2018-03-28 00:18:29 [charset] => UTF-8
         * [seller_email] => wanglina@vshoutao.com [subject] => 璐拱鏈嶅姟
         * [sign] => Qrxnx6uyrIh0qmdZLM/DJgTJMx6Cm49GxiUVmfkI6KXZAFIDpjNfSTMOWxSwS20VWqOO7T6qGHmqcVWhUsCKIGe5Nyf2eHtPlyguISIXJc6xRme/kz39Rjl9ex0j+FKXop3mWNjtlqIx0oBUyz+xgGIo/k+X+n3NV9LkcjRJd3f2K/3s3KfrwAmLiTtMKNqJ0JXGVFEcm3JqoN113vAWCyHQmjsX3wPFFdRjUA2igbQeAAknxfQDuzrkCbCh0seH5UmkCkjYYWs/bHtg7o5FUN8q+GG58SljuvcRjdY8TgLvDyAhjMV+K5Sr2pv2mctJwMH5W2xAq4tZZVDdAVtodA==
         * [body] => 璐拱鏈嶅姟1骞� [buyer_id] => 2088602297295657
         * [invoice_amount] => 0.01 [notify_id] => 07c18326cd4e8685490bffebff3e36fl0p
         * [fund_bill_list] => [{"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}]
         * [notify_type] => trade_status_sync
         * [trade_status] => TRADE_SUCCESS [receipt_amount] => 0.01 [buyer_pay_amount] => 0.01
         * [app_id] => 2018032702453539 [sign_type] => RSA2 [seller_id] => 2088031632394513
         * [gmt_payment] => 2018-03-28 00:18:29 [notify_time] => 2018-03-28 00:18:30
         * [version] => 1.0 [out_trade_no] => 213213213123 [total_amount] => 0.01
         * [trade_no] => 2018032821001004650586768845 [auth_app_id] => 2018032702453539
         * [buyer_logon_id] => 346***@qq.com [point_amount] => 0.00 )
         */
        /** f2f
         * Array ( [gmt_create] => 2018-03-27 21:20:33 [charset] => UTF-8
         * [seller_email] => wanglina@vshoutao.com [subject] => 23234
         * [sign] => WXY9vtyD5Ik4CUoA2OqkFKqPMA069Af1XrckhPCrV7uH/Cnvx6u05LgJ8VbbHHKusY3UFGkPchYXCURlmltWUwel9XBEnFjPYNFybHmtU5Va+AYjKc9GggW4SIvEBvvAGpqV6qVQReC1EneIQEPZXVOc26EFL0tQoYal/CcOX8R0iJknA8Wjz/xsoOnQzLL9f4b8sj78Viu5/nnC+RrBZv4jsTef/QeKhP0RNYqpkZrSjQOIPumkDalGQaQ+a+6a7/uI2y8SKDO8CzI6afynDpoMcx1PDeIb32CkFxxJKZWMBFomVk01/x+NQ4Qk2mRPaFrAdR9RMWa3blBkOXWl8g==
         * [body] => 璐拱鍟嗗搧2浠跺叡15.00鍏�
         * [buyer_id] => 2088602297295657 [invoice_amount] => 0.01 [notify_id] => 6b9d70cd4d7f9f4a36964e616e40c4fl0p
         * [fund_bill_list] => [{"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}]
         * [notify_type] => trade_status_sync
         * [trade_status] => TRADE_SUCCESS [receipt_amount] => 0.01
         * [app_id] => 2018032702453539
         * [buyer_pay_amount] => 0.01 [sign_type] => RSA2
         * [seller_id] => 2088031632394513
         * [gmt_payment] => 2018-03-27 21:22:01 [notify_time] => 2018-03-27 21:22:02
         * [version] => 1.0 [out_trade_no] => 1522156830 [total_amount] => 0.01
         * [trade_no] => 2018032721001004650586539405 [auth_app_id] => 2018032702453539
         * [buyer_logon_id] => 346***@qq.com [point_amount] => 0.00 )
         */
        if ($_REQUEST['trade_status'] == 'TRADE_SUCCESS') {
            $data = array(
                "payid" => $_REQUEST['trade_no'],
                "ptime" => $_REQUEST['gmt_payment'],
                "state" => "已支付",
            );

            $where = array("no" => $_REQUEST['out_trade_no'], "sendsms" => "0");
            $order = M("order")->where($where)->find();
            if ($order) {
                sendSMS($order['phone'], $order['no']);
                $data['sendsms'] = "1";
            }

            $res = M("order")->where($where)->save($data);
            if (!$res) {
                $str = "支付宝-订单：" . $_REQUEST['out_trade_no'] . "支付成功。
                后台数据更新失败,支付时间：" . $_REQUEST['gmt_payment'] .
                    "支付单号：" . $_REQUEST['trade_no'];
                file_put_contents("log.txt", $str . "\r\n", FILE_APPEND);
            }
        }
    }

    /* 微信扫码支付回调方法 */
    public function pay_finish2()
    {
        /**
         * {"appid":"wx373c3b608fe3e39e","attach":"sdsdafsadf",
         * "bank_type":"CFT","cash_fee":"1","fee_type":"CNY",
         * "is_subscribe":"N","mch_id":"1500774721",
         * "nonce_str":"husfie60utgs2qthhjpf25pkba1m05ie",
         * "openid":"oZVPgjkTT9UdsaixyEL9HwblNlcg",
         * "out_trade_no":"1500774721201803281142370000",
         * "result_code":"SUCCESS","return_code":"SUCCESS",
         * "sign":"7E4689F03F0E832E25099BED9F0F9B30","time_end":"20180328114256",
         * "total_fee":"1","trade_type":"NATIVE",
         * "transaction_id":"4200000092201803287063058016"}
         *  [2018-03-28 11:42:56][debug] query:{"appid":"wx373c3b608fe3e39e",
         * "attach":"sdsdafsadf","bank_type":"CFT","cash_fee":"1",
         * "fee_type":"CNY","is_subscribe":"N","mch_id":"1500774721",
         * "nonce_str":"IcduhUfbVgp70XN8","openid":"oZVPgjkTT9UdsaixyEL9HwblNlcg",
         * "out_trade_no":"1500774721201803281142370000","result_code":"SUCCESS",
         * "return_code":"SUCCESS","return_msg":"OK","sign":"1AF6D37649D661E5376D2F2ABDCE9D45",
         * "time_end":"20180328114256","total_fee":"1","trade_state":"SUCCESS","trade_state_desc":"\u652f\u4ed8\u6210\u529f",
         * "trade_type":"NATIVE","transaction_id":"4200000092201803287063058016"}
         */
        require_once $_SERVER['DOCUMENT_ROOT'] . "/api/WechatPay/example/notify.php";
        $result = $notify->result;
        if ($result['result_code'] == 'SUCCESS') {
            $data = array(
                "payid" => $result['transaction_id'],
                "ptime" => date("Y-m-d H:i:s"),
                "state" => "已支付",
            );

            $where = array("no" => $result['out_trade_no'], "sendsms" => "0");
            $order = M("order")->where($where)->find();
            if ($order) {
                sendSMS($order['phone'], $order['no']);
                $data['sendsms'] = "1";
            }

            $res = M("order")->where($where)->save($data);
            if (!$res) {
                $str = "微信扫码支付-订单：" . $result['out_trade_no'] . "支付成功。
                后台数据更新失败,支付时间：" . $data['ptime'] .
                    "支付单号：" . $result['transaction_id'];
                file_put_contents("log.txt", $str . "\r\n", FILE_APPEND);
            }
        }
    }

    /* 根据订单ID来查询支付状态 */
    public function get_pay_result()
    {
        $order = M("order")->where(array("id" => I("request.uuid")))->find();
        if ($order['state'] == "已支付") {
            $this->success("支付成功");
        } else {
            $this->error("支付未成功");
        }
    }

    public function agreement()
    {
        $this->display();
    }

    public function open_type_save()
    {
        $uuid = I("post.uuid");
        $open_type = I("post.open_type");
        if (!$uuid || !$open_type) {
            $this->error("错误的参数");
        }
        $service = M("service")->where(array("id" => $open_type))->find();
        if (!$service) {
            $this->error("错误的参数");
        }

        $data = array(
            "utime" => time(),
            "client" => I("post.client"),
            "type" => I("post.pay_mrch"),
            "refer" => I("post.refer"),
            "service" => $service['name'],
            "service_type" => $service['type'],
            "money" => $service['price'],
        );
        $res = M("order")->where(array("id" => $uuid))->save($data);
        if (!$res) {
            $this->error(M("order")->getLastSql());
            $this->error("订单更新失败");
        }
        $this->success("操作成功");
    }

    public function send_message()
    {
        $data = "SELECT   name,phone,id,is_message,ctime,no,COUNT(distinct phone),TIMESTAMPDIFF(HOUR,ctime,NOW()) 
         from st_order  where TIMESTAMPDIFF(MINUTE,ctime,NOW())>=10 AND  state='未支付' AND to_days(ctime)
         =to_days(now()) AND is_message=0 AND phone NOT IN(SELECT phone FROM st_order WHERE is_message=1 AND
          to_days(ctime)=to_days(now())) GROUP BY phone ORDER BY id";
        $res_list = M()->query($data);
//        dump($res_list);
        $resArr = array();
        if (!empty($res_list)) {
            foreach ($res_list as $key => &$val) {
                $resArr[$key]['name'] = $val['name'];
                $resArr[$key]['id'] = $val['id'];
                $resArr[$key]['phone'] = $val['phone'];
                sendSMS_order($val['phone'],$val['id'],$val['name']);
                sleep(2);
            }
            $name_list = array_column($resArr, 'phone');
            $text = implode(",", $name_list);
            $update = "UPDATE st_order SET is_message = 1 WHERE  phone IN ($text)";
            $res = M()->query($update);
            return $res;
            return $resArr;
        } else {
            return $res_list;
        }

    }

}